<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\common\model;
/**
 * 有关时间的模型
 * Class TimeModel
 * @package app\common\model
 */
class ArtModel
{
    private $endpoint;
    private $token;

    public function __construct($endpoint, $token) {
        $this->endpoint = $endpoint;
        $this->token = $token;
    }

    public function img2img($src, $preset_name)
    {
        $url = "https://api.runpod.ai/v2/{$this->endpoint}/run";
        // 获取图片直接转base64
        $image = base64_encode(file_get_contents($src));
        // 获取图片宽高信息
        $imageInfo = getimagesize($src);
        // 将图片预置到配置项
        $config['init_images'] = [ $image ];
        // 根据图片宽高判断是横向还是竖向
        if ($imageInfo[0] < $imageInfo[1]) {
            $config['width'] = 768;
            $config['height'] = 1024;
        } else {
            $config['width'] = 1024;
            $config['height'] = 768;
        }
        // 根据出图类型获取预设值
        $preset = json_decode(file_get_contents($preset_name.'.json'), true);
        // 配置项+预设值合并
        $payload = array_merge($config, $preset);
        $data = [
            'input' => [
                'api' => '/sdapi/v1/img2img',
                'payload' => $payload,
                'method' => 'post'
            ]
        ];
        $result = $this->curlPost($url, $data);
        return $result;
    }

    public function get_status($id)
    {
        $url = "https://api.runpod.ai/v2/{$this->endpoint}/status/{$id}";
        $data = [];
        $result = $this->curlPost($url, $data);

        if (isset($result['error'])) { return $result['error']; }
        if (isset($result['output']['err'])) { return $result['output']['err']; }

        if ($result['status'] == 'COMPLETED') {
            $data = json_decode(file_get_contents($result['output']['output_url']), true);
            // print_r($data);
            // 保存至本地，图片后缀为固定png格式
            file_put_contents($result['id'].'.png', base64_decode($data['images'][0]));
            return 'AI改画成功！已保存至本地。'."\r\n";
        } else if ($result['status'] == 'IN_PROGRESS') {
            // 由于预估时间太短，所以毫秒至秒的换算只除以10
            return 'AI改画中，预估时间：'.round($result['delayTime']/10).'秒'."\r\n";
        }
        return '正在排队改画中，请稍候'."\r\n";
    }

    public function get_controlnet_models()
    {
        $url = "https://api.runpod.ai/v2/{$this->endpoint}/runsync";
        $data = [
            'input' => [
                'api' => '/controlnet/model_list?update=true'
            ]
        ];
        $result = $this->curlPost($url, $data);
        return $result;
    }

    public function curlPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            "Authorization: Bearer {$this->token}"
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }
}